package com.github.hgkmail.hello.cmd;

import com.github.hgkmail.hello.cmd.helper.*;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaField;
import com.thoughtworks.qdox.model.JavaMethod;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext;

import java.util.ArrayList;
import java.util.List;

import static java.lang.System.out;

/**
 * 生成 DO.java
 *
 * @author kimhuang
 * @date 2021/2/12
 */
public class GenDataObject extends BaseParseClass {

    public static void main(String[] args) {
        new GenDataObject().run();
    }

    @Override
    public void run() {
        parseClass(new RenderDataObject());
    }

    private class RenderDataObject implements ParseClassListener {
        private ClazzInfo clazz = new ClazzInfo();
        private List<FieldInfo> generalFields = new ArrayList<>();

        RenderDataObject() {
        }

        @Override
        public void onStart(JavaClass jClass) {
            clazz = new ClazzInfo();
            clazz.setName(jClass.getSimpleName());
            clazz.setAuthor(DocTagUtil.firstTagValue(jClass, "author", ""));
            clazz.setDate(DocTagUtil.firstTagValue(jClass, "date", ""));
            clazz.setComment(DocTagUtil.firstTagValue(jClass, "comment", ""));
        }

        @Override
        public void onField(JavaClass jClass, JavaField jField) {
            FieldInfo fieldInfo = new FieldInfo();
            fieldInfo.setName(jField.getName());
            fieldInfo.setType(jField.getType().getSimpleName());
            fieldInfo.setComment(DocTagUtil.firstTagValue(jField, "comment", ""));
            fieldInfo.setDefaultVal(DocTagUtil.firstTagValue(jField, "default", ""));

            fieldInfo.setHasComment(false);
            if (StringUtils.isNotBlank(fieldInfo.getComment())) {
                fieldInfo.setHasComment(true);
            }

            fieldInfo.setHasDefault(false);
            if (StringUtils.isNotBlank(fieldInfo.getDefaultVal())) {
                fieldInfo.setHasDefault(true);
            }

            generalFields.add(fieldInfo);
        }

        @Override
        public void onMethod(JavaClass jClass, JavaMethod jMethod) {
            //nothing
        }

        @Override
        public void onEnd(JavaClass jClass) {
            renderVm("code-maker/generate/data_object_java.vm", new RenderListener() {
                @Override
                public void beforeRender(VelocityContext vContext) {
                    vContext.put("clazz", clazz);
                    vContext.put("generalFields", generalFields);
                }

                @Override
                public void afterRender(VelocityContext vContext, String result) {
                    out.println(result);
                }
            });
        }

    }

}
